package coletor.digitos.dtmf;

import java.telephony.*;
import java.telephony.events.*;
import java.telephony.media.*;
import java.telephony.media.events.*;


class DtmfCallObserver implements  MediaCallObserver {

  /*
   * This CallObserver will be notified of Call events. We want to first
   * answer the incoming telephone call, and then perform the neccessary
   * media actions to perform DTMF.
   */
  public void callChangedEvent(CallEv evlist[]) {

    for (int i = 0; i < evlist.length; i++) {
      CallEv ev = evlist[i];

      if (ev instanceof TermConnRingingEv) {

        /* Answer the phone. */
        TerminalConnection tc = ((TermConnEv)ev).getTerminalConnection();
        try {
          tc.answer();
        } catch (Exception excp) {
          // Handle Exceptions
        }
      }
      else if (ev instanceof MediaTermConnAvailableEv) {

        /* We want to start DTMF-detection
        TerminalConnection tc = (TermConnEv)ev.getTerminalConnection();
        MediaTerminalConnection mtc = (MediaTerminalConnection)tc;

        try {
          mtc.setDtmfDetection(true);
        } catch (Exception excp) {
          // Handle exceptions
        }
      }
      else if (ev instanceof MediaTermConnUnavailableEv) {

        /* Turn off DTMF-detection */
        TerminalConnection tc = (TermConnEv)ev.getTerminalConnection();
        MediaTerminalConnection mtc = (MediaTerminalConnection)tc;

        try {
          mtc.setDtmfDetection(false);
        } catch (Exception excp) {
          // Handle exceptions
        }
      }
      else if (ev instanceof MediaTermConnDtmfEv) {

        /* Print out the DTMF digits */
        char digit = ((MediaTermConnDtmfEv)ev).getDigit();
        System.out.println("detected DTMF: " + digit);
      }
    }
  }
}

